#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: musics.py
@contact: zwb15083976291@163.com
@time: 2021/12/03
"""
from django.utils.decorators import method_decorator

from admin.serializers.musics import MusicsSerializer, PostMusicsSerializer, UpdateMusicsSerializer, \
    DeleteMusicsSerializer
from common.models import BlogMusics
from utils.filters.views_filters import SearchMusicsFilter
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.serializers.serializer import PaginatorSerializer
from utils.user_authentication import allow_admin_user
from utils.views import BasePaginateGenericAPIView


@method_decorator(allow_admin_user, name='dispatch')
class ManagementMusicsView(BasePaginateGenericAPIView):
    diff_methods_request_params = dict(
        get=dict(optional=['pageNum', 'pageSize', 'search'], defualt_value=dict(pageNum=1, pageSize=10)),
        post=dict(required=['music_cover', 'music_artist', 'music_name', 'music_url']),
        put=dict(required=['id', 'music_cover', 'music_artist', 'music_name', 'music_url']),
        delete=dict(required=['id']))
    diff_methods_serializer_class = dict(get=PaginatorSerializer, post=PostMusicsSerializer, put=UpdateMusicsSerializer,
                                         delete=DeleteMusicsSerializer)

    filter_backends = [SearchMusicsFilter]

    def get(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        queryset = self.filter_queryset(BlogMusics.objects.all())
        paginator, models = self.paginate_queryset(queryset=queryset, params_dict=self.serializer.validated_data)
        return CommonResponse(data=self.get_paginated_response(self.serializer.validated_data, paginator,
                                                               MusicsSerializer(instance=models, many=True).data))

    def post(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        self.serializer.save()
        return CommonResponse(data=self.serializer.data)

    def put(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        self.serializer.select_field_update_obj()
        return CommonResponse(data=self.serializer.data)

    def delete(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        self.serializer.select_field_delete_obj()
        return CommonResponse(data=self.serializer.data)
